package com.ems.sys.controller;

import cn.hutool.core.lang.UUID;
import com.ems.sys.utils.Const;
import com.ems.sys.utils.RedisUtil;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Collection;

@Controller
public class LoginController {

    @RequestMapping("/hello")
    public String hello() {
        //这边我们,默认是返到templates下的login.html
        return "login";
    }

    @RequestMapping("/login_error")
    public String login_error() {
        //这边我们,默认是返到templates下的login.html
        return "login_error";
    }

    @GetMapping("/sys/getuserByRole")
    @ResponseBody
//    @CrossOrigin(origins = "http://localhost:8090/**")
    public Collection<? extends GrantedAuthority> getUser(){
        SecurityContext context = SecurityContextHolder.getContext();
        System.out.println(context.getAuthentication());
        Authentication authentication = context.getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        System.out.println(principal.getAuthorities());
       return principal.getAuthorities();
    }

    @Autowired
    Producer producer;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private DefaultKaptcha captchaProducer;


    @GetMapping("/captcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = captchaProducer.createText();
            String key = UUID.randomUUID().toString();
            redisUtil.hset(Const.CAPTCHA_KEY, key, createText, 120);
            httpServletRequest.getSession().setAttribute("verifyKey", key);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = captchaProducer.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}
